<template>

	<view class="html2canvas-wrap">
		<view id="container">
			<view class="content">
				<view>
					<text class="title">{{ title }}</text>
				</view>
				<view class="picture">
					<image crossorigin="anonymous" :src="gongzhang"></image>
				</view>
				<button @click="canvasToImage.generateImage">保存图片</button>
			</view>
		</view>

		<view class="preview">
			<image crossorigin="anonymous" :src="preview"></image>
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				gongzhang: 'https://img2.baidu.com/it/u=2243573419,589412055&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
				preview: ''
			}
		},
		mounted() {},
		methods: {
			getSaveImg(data) {
				// console.log('base64data', data);
				let _this = this;
				let base64data = data.base64data;
				let bitmap = new plus.nativeObj.Bitmap("test");
				bitmap.loadBase64Data(base64data, function() {
					console.log("加载Base64图片数据成功");

					let url = '_downloads/test2.png';

					bitmap.save(url, {}, function(i) {
						console.log('保存图片成功：' + JSON.stringify(i));
						_this.preview = i.target
						// 保存图片到相册
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: function() {
								uni.showToast({
									title: '图片保存成功',
									icon: 'none'
								})
								// 图片保存成功后，将临时保存的图片删除
								plus.io.resolveLocalFileSystemURL(
									url,
									function(entry) {
										entry.getMetadata(function(metadata) {
											// console.log("fileCount=" + metadata.fileCount);
											entry
												.remove(); //删除单个文件 _downloads/改文件名

										});
									},
									function(error) {
										// uni.showToast({ title: "下载文件" });
										console.log("error" + error);
									}
								);
								bitmap.clear()
							}
						});
						bitmap.clear();
					}, function(e) {
						onsole.log('保存图片失败：' + JSON.stringify(e));
						bitmap.clear();
					});
				}, function() {
					console.log('加载Base64图片数据失败：' + JSON.stringify(e));
					bitmap.clear();
				});
			},
		}
	}
</script>

<script module="canvasToImage" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		data() {
			return {}
		},
		methods: {
			// 获取设备的Dpr值
			getDpr() {
				if (window.devicePixelRatio && window.devicePixelRatio > 1) {
					return window.devicePixelRatio;
				}
				return 1;
			},
			/**
			 * 将传入值转为整数
			 * @param value
			 * @returns {number}
			 */
			parseValue(value) {
				return parseInt(value, 10);
			},
			generateImage(event, ownerInstance) {
				var _this = this;

				var scanTextElem = document.getElementById('container');
				scanTextElem.style.opacity = '1';

				// 获取想要转换的dom节点
				var dom = document.getElementById('container');
				var box = window.getComputedStyle(dom);

				// dom节点计算后宽高
				var width = _this.parseValue(box.width);
				var height = _this.parseValue(box.height);

				// 获取像素比
				var scaleBy = _this.getDpr();

				// 创建自定义的canvas元素
				var canvas = document.createElement('canvas');

				// 设置canvas元素属性宽高为 DOM 节点宽高 * 像素比
				canvas.width = width * scaleBy;
				canvas.height = height * scaleBy;

				// 设置canvas css 宽高为DOM节点宽高
				canvas.style.width = width + 'px';
				canvas.style.height = height + 'px';

				// 获取画笔
				var context = canvas.getContext('2d');

				// 将所有绘制内容放大像素比倍
				context.scale(scaleBy, scaleBy);

				// 设置需要生成的图片的大小，不限于可视区域（即可保存长图）
				var w = document.getElementById('container').style.width;
				var h = document.getElementById('container').style.height;

				// 这儿的width、height一定得要有值，不然会保存失败
				html2canvas(dom, {
					allowTaint: false,
					width: window.clientWidth,
					height: window.clientHeight,
					backgroundColor: 'green',
					useCORS: true
				}).then(function(canv) {
					// 将canvas转换成图片渲染到页面上
					let url = canv.toDataURL('image/png'); // base64数据
					ownerInstance.callMethod('getSaveImg', {
						base64data: url
					})
				});
			},

		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: red;
	}

	.preview {
		text-align: center;
	}
</style>